package com.mazaiting.imqq.presenter.user;

import android.text.TextUtils;
import cn.bmob.newim.BmobIM;
import cn.bmob.newim.bean.BmobIMConversation;
import cn.bmob.newim.bean.BmobIMMessage;
import cn.bmob.newim.bean.BmobIMUserInfo;
import cn.bmob.newim.event.MessageEvent;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.LogInListener;
import cn.bmob.v3.listener.QueryListener;
import cn.bmob.v3.listener.SaveListener;
import com.mazaiting.imqq.model.bean.Friend;
import com.mazaiting.imqq.model.bean.UserInfo;
import com.mazaiting.imqq.presenter.listener.QueryUserListener;
import com.mazaiting.imqq.presenter.listener.UpdateCacheListener;
import com.mazaiting.imqq.presenter.base.Manager;
import com.orhanobut.logger.Logger;
import java.util.List;

/**
 * Created by mazaiting on 2017/9/5.
 */

public class UserManager extends Manager {


  protected UserManager(){ }

  public static UserManager getInstance(){
    return InnerManager.mManager;
  }

  /**
   * 获取当前用户
   * @return
   */
  public UserInfo getCurrentUser() {
    return BmobUser.getCurrentUser(UserInfo.class);
  }

  /**
   * 同意添加朋友
   * @param friendInfo
   * @param saveListener
   */
  public void agreeAddFriend(UserInfo friendInfo, SaveListener<String> saveListener) {
    Friend friend = new Friend();
    friend.setUserInfo(getCurrentUser());
    friend.setFriendUserInfo(friendInfo);
    friend.save(saveListener);
  }

  /**
   * 查询全部好友
   */
  public void queryFriends(final FindListener<Friend> listener) {
    BmobQuery<Friend> query = new BmobQuery<>();
    UserInfo currentUser = BmobUser.getCurrentUser(UserInfo.class);
    query.addWhereEqualTo("userInfo", currentUser); // 用户等于当前用户
    query.include("friendUserInfo"); // 包含列
    query.order("-updatedAt"); // 更新时间
    query.findObjects(new FindListener<Friend>() {
      @Override public void done(List<Friend> list, BmobException e) {
        listener.done(list, e);
      }
    });
  }

  private static class InnerManager{
    public static final UserManager mManager = new UserManager();
  }

  /**
   * 注册用户
   * @param username 用户名
   * @param password 密码
   * @param pwdAgain 确认密码
   * @param listener 登录监听
   */
  public void registerUser(final String username, String password, String pwdAgain, final LogInListener<UserInfo> listener){
    if (TextUtils.isEmpty(username)) {
      listener.done(null, new BmobException(CODE_NULL, "请填写用户名"));
      return;
    }
    if (TextUtils.isEmpty(password)) {
      listener.done(null, new BmobException(CODE_NULL, "请填写密码"));
      return;
    }
    if (TextUtils.isEmpty(pwdAgain)) {
      listener.done(null, new BmobException(CODE_NULL, "请填写确认密码"));
      return;
    }
    if (!password.equals(pwdAgain)) {
      listener.done(null, new BmobException(CODE_NULL, "两次输入的密码不一致，请重新输入"));
      return;
    }
    final UserInfo info = new UserInfo();
    info.setUsername(username);
    info.setPassword(password);
    info.signUp(new SaveListener<UserInfo>() {
      @Override public void done(UserInfo userInfo, BmobException e) {
        if (listener != null){
          listener.done(info, e);
        }
      }
    });
  }

  /**
   * 用户登录
   * @param username 用户名
   * @param password 密码
   * @param listener 登录监听
   */
  public void login(String username, String password, final LogInListener<UserInfo> listener){
    if (TextUtils.isEmpty(username)) {
      listener.done(null, new BmobException(CODE_NULL, "请填写用户名"));
      return;
    }
    if (TextUtils.isEmpty(password)) {
      listener.done(null, new BmobException(CODE_NULL, "请填写密码"));
      return;
    }

    UserInfo userInfo = new UserInfo();
    userInfo.setUsername(username);
    userInfo.setPassword(password);
    userInfo.login(new SaveListener<UserInfo>() {
      @Override public void done(UserInfo userInfo, BmobException e) {
        if (listener != null){
          listener.done(userInfo, e);
        }
      }
    });
  }

  /**
   * 退出登录
   */
  public void logout(){
    BmobUser.logOut();
  }

  /**
   * 更新用户资料和会话资料
   */
  public void updateUserInfo(MessageEvent event, final UpdateCacheListener listener) {
    // 获得回话消息
    final BmobIMConversation conversation = event.getConversation();
    // 获取用户信息
    final BmobIMUserInfo info = event.getFromUserInfo();
    // 获取消息
    final BmobIMMessage message = event.getMessage();
    // BmobIMMessage{id=null, fromId=e976bd877c, toId=a4287fd523, msgType=txt, content='你', extra={"level":"1"},
    // conversationType=1, conversationId=e976bd877c, sendStatus=4, receiveStatus=0, createTime=1504768793374, updateTime=1504768793374, isTransient=false}
    String username = info.getName();
    String avatar = info.getAvatar(); // 为空
    String title = conversation.getConversationTitle();
    String icon = conversation.getConversationIcon();// 为空
    // TODO SDK内部将新会话的会话标题用objectId表示，因此需要比对用户名和私聊会话标题，后续会根据会话类型进行判断
    Logger.e(title +"----------" + username);
    if (!title.equals(username)){
      queryUserInfo(info.getUserId(), new QueryUserListener(){
        @Override public void done(UserInfo userInfo, BmobException e) {
          if (e == null){
            String name = userInfo.getUsername();
            String avatar = userInfo.getAvatar();
            conversation.setConversationIcon(avatar);
            conversation.setConversationTitle(name);
            // 更新用户资料，用于在会话页面、聊天页面以及个人信息页面显示
            BmobIM.getInstance().updateUserInfo(info);
            // 更新会话资料-如果消息是暂态消息，则不更新会话资料
            if (!message.isTransient()){
              BmobIM.getInstance().updateConversation(conversation);
            }
          } else {
            Logger.e(e.toString());
          }
          listener.done(null);
        }
      });
    } else {
      listener.done(null);
    }
  }

  /**
   * 查询指定用户信息
   * @param userId objectId
   * @param queryUserListener 查询用户监听
   */
  private void queryUserInfo(String userId, final QueryUserListener queryUserListener) {
    BmobQuery<UserInfo> query = new BmobQuery<>();
    query.getObject(userId, new QueryListener<UserInfo>() {
      @Override public void done(UserInfo userInfo, BmobException e) {
        if (queryUserListener != null){
          queryUserListener.done(userInfo, e);
        }
      }
    });
  }
}
